package com.my.common.util.network;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.regex.Pattern;

/**
 * @author: marshal
 * @date: 2023-07-06 14:59
 */
@UtilityClass
@Slf4j
public class NetworkUtils {

    private static final Integer TIMEOUT = 3000;

    /**
     * 判断IP是否可以连接
     *
     * @param ip      IP
     * @param timeout 超时时间
     * @return ture/false
     */
    public boolean isIpReachable(String ip, int timeout) {
        if (timeout <= 0) {
            timeout = TIMEOUT;
        }
        try {
            return InetAddress.getByName(ip).isReachable(timeout);
        } catch (IOException e) {
            log.debug("ip {} is not reachable", ip);
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 判断IP和端口是否可以连接
     *
     * @param ip   ip
     * @param port 端口
     * @return true/false
     */
    public boolean isIpPortConnectable(String ip, int port) {
        try (Socket socket = new Socket()) {
            socket.connect(new InetSocketAddress(ip, port));
        } catch (IOException e) {
            log.debug("ip {} and port {} is not reachable", ip, port);
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     *  IP 校验
     *
     * @param ip IP
     * @return true/false
     */
    public boolean checkIp(String ip) {
      String regexIpv4 = "((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}";
      return Pattern.compile(regexIpv4).matcher(ip).matches();
    }
}
